using System;

namespace Se.Framework.Common.Config
{
    public static class Configuration
    {
        private static ConfigurationValues current;
        public static ConfigurationValues Current
        {
            get
            {
                if(current == null)
                {
                    current = ObjectRegistry.Current.Resolve<ConfigurationValues>();
                    current.LoadValues();
                }
                return current;
            } 
        }

        public static void ReloadValues()
        {
            Current.LoadValues();
        }

        /// <summary>
        /// Runs the given code only if the key is present in the manager
        /// </summary>
        /// <param name="manager">Manager to be used</param>
        /// <param name="key">Search Key</param>
        /// <param name="action">Action to be executed</param>
        public static void ExecuteIfExists(this IConfigurationManager manager, string key, Action<string> action)
        {
            if (!string.IsNullOrEmpty(manager.AppSettings[key]))
            {
                action(manager.AppSettings[key]);
            }
        }

        /// <summary>
        /// Runs the given code only if the key is present in the manager and the result is and integer, otherwise use the default value
        /// </summary>
        /// <param name="manager">Manager to be used</param>
        /// <param name="key">Search Key</param>
        /// <param name="action">Action to be executed</param>
        /// <param name="defaultValue">Default value in case of an error.</param>
        public static void ExecuteIfExists(this IConfigurationManager manager, string key, Action<int> action, int defaultValue)
        {
            int value = defaultValue;
            if (!int.TryParse(manager.AppSettings[key], out value))
            {
                action(defaultValue);
            }
            else
            {
                action(value);
            }
        }

        /// <summary>
        /// Runs the given code only if the key is present in the manager and the result is and integer, otherwise use the default value
        /// </summary>
        /// <param name="manager">Manager to be used</param>
        /// <param name="key">Search Key</param>
        /// <param name="action">Action to be executed</param>
        /// <param name="defaultValue">Default value in case of an error.</param>
        public static void ExecuteIfExists(this IConfigurationManager manager, string key, Action<bool> action, bool defaultValue)
        {
            bool value = defaultValue;
            if (!bool.TryParse(manager.AppSettings[key], out value))
            {
                action(defaultValue);
            }
            else
            {
                action(value);
            }
        }
    }
}